package com.luoxiang.socialandroid.activity;

import static com.drake.softinput.SoftInputKt.setWindowSoftInput;
import static com.drake.softinput.SoftInputUtilsKt.hasSoftInput;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.drake.softinput.SoftInputUtilsKt;
import com.faceunity.core.entity.FUBundleData;
import com.faceunity.core.entity.FURenderInputData;
import com.faceunity.core.entity.FURenderOutputData;
import com.faceunity.core.enumeration.FUAITypeEnum;
import com.faceunity.core.enumeration.FUInputTextureEnum;
import com.faceunity.core.faceunity.FUAIKit;
import com.faceunity.core.faceunity.FURenderKit;
import com.faceunity.core.model.facebeauty.FaceBeauty;
import com.faceunity.core.model.prop.expression.ExpressionRecognition;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.utils.DensityUtil;
import com.luoxiang.lib_common.utils.MmkvUtil;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.VideoChatAdapter;
import com.luoxiang.socialandroid.app.MyAppliaction;
import com.luoxiang.socialandroid.bean.KouFeiBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.OurinfoBean;
import com.luoxiang.socialandroid.bean.SendMessageBean;
import com.luoxiang.socialandroid.dialog.GiftSuspensionDialog;
import com.luoxiang.socialandroid.dialog.SuspendedWindowDialog;
import com.luoxiang.socialandroid.event.HangUpEvent;
import com.luoxiang.socialandroid.face.DemoConfig;
import com.luoxiang.socialandroid.face.data.source.FaceBeautySource;
import com.luoxiang.socialandroid.service.FloatVideoWindowService;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.DelayUtil;
import com.luoxiang.socialandroid.utils.LoopUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.netease.lava.nertc.sdk.NERtcEx;
import com.netease.lava.nertc.sdk.video.NERtcEncodeConfig;
import com.netease.lava.nertc.sdk.video.NERtcVideoConfig;
import com.netease.lava.nertc.sdk.video.NERtcVideoFrame;
import com.netease.lava.nertc.sdk.video.NERtcVideoView;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.yunxin.kit.chatkit.ui.bean.GiftMessageBean;
import com.netease.yunxin.kit.chatkit.ui.custom.GiftAttachment;
import com.netease.yunxin.kit.chatkit.ui.dialog.GiftDialog;
import com.netease.yunxin.kit.chatkit.ui.dialog.GiftGifDialog;
import com.netease.yunxin.nertc.nertcvideocall.model.NERTCCallingDelegate;
import com.netease.yunxin.nertc.ui.base.AVChatSoundPlayer;
import com.netease.yunxin.nertc.ui.base.CommonCallActivity;
import com.netease.yunxin.nertc.ui.base.SoundHelper;
import com.netease.yunxin.nertc.ui.p2p.NERtcCallDelegateForP2P;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicLong;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class TestActivity extends CommonCallActivity {
    private boolean startPreview = false;
    private String token, name;
    private long rtcchannelId;
    private ImageView ic_songliwu;
    private TextView tvDuration;
    private RecyclerView rv_gifts;
    private TextView now_coin;
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private Button btn_sendgift;
    private String usersid, CallLogId;
    private String callerAccId, p2pCalledAccId;
    private RelativeLayout rele_hujiaofang;
    private TextView tv_callername, tv_microphone, tv_camera;
    private ImageView img_heads;
    private TextView tv_zhuboshouyi;
    private String url = "https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/";
    private TextView tv_waitaccept;
    private ImageView icCamera;
    private Button ic_fanzhuan;
    private ImageView icMicrophone;
    private LinearLayout linearHostInfo;
    private int flag;
    private boolean isOpenCamera = true;
    private boolean isOpenMicrophone = true;
    private boolean isTheLocalTime = false;
    private boolean isFirstInit = false;
    private LoopUtil loopUtil;
    private String channelName;
    private Integer acceptcode = null;
    private String acceptmsg;
    private String city;
    private ImageView img_location, imageLevel;
    private ImageView imageSmallWindow;
    public static OurinfoBean ourinfoBean;
    private ImageView imageChat;
    private RecyclerView chatView;
    private EditText chatEdit;
    private Button chatSend;
    private RelativeLayout editView;
    private VideoChatAdapter adapter;
    private int sendIndex;

    private SoundHelper soundHelper = new SoundHelper() {
        @Override
        public boolean isEnable() {
            return true;
        }

        @Nullable
        @Override
        public Integer soundResources(@NonNull AVChatSoundPlayer.RingerTypeEnum ringerTypeEnum) {
            Integer source = R.raw.viedio_callnow;
            if (ringerTypeEnum == AVChatSoundPlayer.RingerTypeEnum.CONNECTING) {
                source = R.raw.viedio_callnow;
            } else if (ringerTypeEnum == AVChatSoundPlayer.RingerTypeEnum.NO_RESPONSE) {
                source = R.raw.viedio_callnow;
            } else if (ringerTypeEnum == AVChatSoundPlayer.RingerTypeEnum.PEER_BUSY) {
                source = R.raw.viedio_callnow;
            } else if (ringerTypeEnum == AVChatSoundPlayer.RingerTypeEnum.PEER_REJECT) {
                source = R.raw.viedio_callnow;
            } else if (ringerTypeEnum == AVChatSoundPlayer.RingerTypeEnum.RING) {
                source = R.raw.viedio_callnow;
            }
            return source;
        }
    };

    private void initScreenRecorderBuild() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA


        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {

                } else {
                    ToastUtils.showShort(R.string.mi_camera_video_quanxian);
                }
            }
        });
    }

    @Override
    protected int provideLayoutId() {
        return R.layout.activity_test;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarTranslucent();
        initScreenRecorderBuild();
        //禁止页面被截屏、录屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        EventBus.getDefault().register(this);
        tv_waitaccept = findViewById(R.id.tv_waitaccept);
        tv_zhuboshouyi = findViewById(R.id.tv_zhuboshouyi);
        tvDuration = findViewById(R.id.tvDuration);
        tv_microphone = findViewById(R.id.tv_microphone);
        tv_camera = findViewById(R.id.tv_camera);
        img_location = findViewById(R.id.img_location);
        imageSmallWindow = findViewById(R.id.imageSmallWindow);
        chatView = findViewById(R.id.recyclerChat);
        editView = findViewById(R.id.editChat);
        chatEdit = findViewById(R.id.editView);
        imageChat = findViewById(R.id.imageChat);
        chatSend = findViewById(R.id.buttonSend);
        adapter = new VideoChatAdapter();
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(TestActivity.this);
        linearLayoutManager.setStackFromEnd(true);
        chatView.setAdapter(adapter);
        chatView.setLayoutManager(linearLayoutManager);
        chatView.setHasFixedSize(true);


        setWindowSoftInput(TestActivity.this, editView, editView, chatEdit, 0, false, () -> {
            if (!hasSoftInput(TestActivity.this)) {
                editView.setVisibility(View.GONE);
            }
            return null;
        });
        chatSend.setOnClickListener(view -> {
            String text = chatEdit.getText().toString();
            if (TextUtils.isEmpty(text)) {
                ToastUtils.showShort("不能发送空消息");
                return;
            }
            SessionTypeEnum sessionType = SessionTypeEnum.P2P;
            IMMessage textMessage = MessageBuilder.createTextMessage(String.valueOf(usersid), sessionType, text);
            sendIndex = chatList.size();
            NIMClient.getService(MsgService.class).sendMessage(textMessage, false).setCallback(new RequestCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                }

                @Override
                public void onFailed(int code) {
                    chatList.get(sendIndex).setViolations(true);
                    adapter.notifyItemChanged(sendIndex);
                }

                @Override
                public void onException(Throwable exception) {
                }
            });
            SoftInputUtilsKt.hideSoftInput(TestActivity.this);
            editView.setVisibility(View.GONE);
            chatEdit.clearFocus();
            chatEdit.getText().clear();
        });
        imageChat.setOnClickListener(view -> {
            editView.setVisibility(View.VISIBLE);
            SoftInputUtilsKt.showSoftInput(chatEdit);
        });

        Integer hostAudit = MmkvUtil.INSTANCE.decodeInt(HOSTAUDIT);
        if (hostAudit != null && hostAudit == 1) {
            findViewById(R.id.ic_camera).setVisibility(View.GONE);
            findViewById(R.id.tv_camera).setVisibility(View.GONE);
        } else {
            findViewById(R.id.ic_camera).setVisibility(View.VISIBLE);
            findViewById(R.id.tv_camera).setVisibility(View.VISIBLE);
        }
        // 当前页面启动是主叫还是被叫
        AVChatSoundPlayer.Companion.instance().play(this, AVChatSoundPlayer.RingerTypeEnum.RING);
        if (!getCallParam().isCalled()) {
            impcall(EXTRA, p2pCalledAccId, token);
            flag = 1;//表示主叫
            // 启动呼叫
            AVChatSoundPlayer.Companion.instance().play(TestActivity.this, AVChatSoundPlayer.RingerTypeEnum.CONNECTING);
            doCall(null, null);
            findViewById(R.id.callerOperationGroup).setVisibility(View.VISIBLE);

            // 主叫取消
            View cancel = findViewById(R.id.imageActiveRejection);
            cancel.setOnClickListener(v -> {
                doCancel(null);
                finishAndRemoveTask();
            });

            // 设置摄像头为前置
            NERtcVideoConfig config = new NERtcVideoConfig();
            config.frameRate = NERtcEncodeConfig.NERtcVideoFrameRate.FRAME_RATE_FPS_15;
            config.width = 1920;
            config.height = 1080;
            config.frontCamera = true;
            NERtcEx.getInstance().setLocalVideoConfig(config);

            // 呼叫方的本地预览
            NERtcVideoView videoViewLocalBig = findViewById(R.id.videoViewLocalBig);
            videoViewLocalBig.setVisibility(View.VISIBLE);
            getVideoCall().setupLocalView(videoViewLocalBig);
            NERtcEx.getInstance().startVideoPreview();
            videoViewLocalBig.setMirror(false);
            startPreview = true;
        } else {
            // 设置摄像头为前置
            NERtcVideoConfig config = new NERtcVideoConfig();
            config.frameRate = NERtcEncodeConfig.NERtcVideoFrameRate.FRAME_RATE_FPS_15;
            config.width = 1920;
            config.height = 1080;
            config.frontCamera = true;
            NERtcEx.getInstance().setLocalVideoConfig(config);
            flag = 0;//表示被叫
            impcall(EXTRA, callerAccId, token);
            findViewById(R.id.calledOperationGroup).setVisibility(View.VISIBLE);

            // 被叫拒绝
            View reject = findViewById(R.id.ivReject);
            reject.setOnClickListener(v -> {
                doReject(null);
                finishAndRemoveTask();
            });

            // 被叫接受
            View accept = findViewById(R.id.ivAccept);

            accept.setOnClickListener(new CustomClickListener() {
                @Override
                protected void onSingleClick() {
                    if (acceptcode == null) {
                        ToastUtils.showShort(R.string.mi_zhengzaijietongqingshaodeng);
                    } else if (acceptcode == 0) {
                        doAccept(null);
                    } else {
                        ToastUtils.showShort(acceptmsg);
                        doReject(null);
                    }
                }

                @Override
                protected void onFastClick() {

                }
            });
        }
        facialTreatment();
        View hangup = findViewById(R.id.ivHangUp);
        hangup.setOnClickListener(v -> {
            doHangup(null);
            getstopCall(EXTRA, rtcchannelId + "", token);
            finishAndRemoveTask();
            Intent intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
        });
        imageSmallWindow.setOnClickListener(v -> {
            startVideoService();
        });
        ic_songliwu = findViewById(R.id.ic_songliwu);
        icCamera = findViewById(R.id.ic_camera);
        ic_fanzhuan = findViewById(R.id.ic_fanzhuan);
        icMicrophone = findViewById(R.id.ic_microphone);
        ic_songliwu.setOnClickListener(view -> {
            GiftDialog giftDialog;
            if (CallLogId != null) {
                //表示用户送礼
                giftDialog = new GiftDialog(TestActivity.this, usersid, 2, CallLogId);
                giftDialog.setOnSendSuccess(giftMessageBean -> {
                    MsgAttachment attachment = new GiftAttachment(giftMessageBean);
                    IMMessage customMessage =
                            MessageBuilder.createCustomMessage(String.valueOf(usersid), SessionTypeEnum.P2P, getString(R.string.mi_liwuxiaoxi), attachment);
                    NIMClient.getService(MsgService.class).sendMessage(customMessage, false);
                    return null;
                });
            } else {
                //表示主播送礼
                giftDialog = new GiftDialog(TestActivity.this, usersid, 2, "");
                giftDialog.setOnSendSuccess(giftMessageBean -> {
                    MsgAttachment attachment = new GiftAttachment(giftMessageBean);
                    IMMessage customMessage =
                            MessageBuilder.createCustomMessage(String.valueOf(usersid), SessionTypeEnum.P2P, getString(R.string.mi_liwuxiaoxi), attachment);
                    NIMClient.getService(MsgService.class).sendMessage(customMessage, false);
                    return null;
                });
            }
            new XPopup.Builder(TestActivity.this)
                    .moveUpToKeyboard(true)
                    .asCustom(giftDialog)
                    .show();
        });
        icCamera.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                isOpenCamera = !isOpenCamera;
                getVideoCall().muteLocalVideo(!isOpenCamera);
                if (isOpenCamera) {
                    findViewById(R.id.constraintCloseMicrophone).setVisibility(View.GONE);
                    findViewById(R.id.videoViewLocalSmall).setVisibility(View.VISIBLE);
                    icCamera.setImageDrawable(ContextCompat.getDrawable(TestActivity.this, R.mipmap.icon_qiehuanshexiangtou_66_nor));
                    tv_camera.setText("摄像头已打开");
                } else {
                    findViewById(R.id.constraintCloseMicrophone).setVisibility(View.VISIBLE);
                    findViewById(R.id.videoViewLocalSmall).setVisibility(View.GONE);
                    icCamera.setImageDrawable(ContextCompat.getDrawable(TestActivity.this, R.mipmap.icon_qiehuanshexiangtou_66_yes));
                    tv_camera.setText("摄像头已关闭");
                }
            }

            @Override
            protected void onFastClick() {

            }
        });
        ic_fanzhuan.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                NERtcEx.getInstance().switchCamera();
//                NERtcVideoView videoViewLocalSmall = findViewById(R.id.videoViewLocalSmall);
//                getVideoCall().setupLocalView(findViewById(R.id.videoViewLocalSmall));
//                videoViewLocalSmall.setMirror(true);
//                NERtcVideoView videoViewLocalSmall2 = findViewById(R.id.videoViewRemote);
//                getVideoCall().setupRemoteView(findViewById(R.id.videoViewRemote), usersid);
//                videoViewLocalSmall2.setMirror(true);
//                NERtcVideoView videoViewLocalSmall3 = findViewById(R.id.videoViewLocalSmall);
//                getVideoCall().setupLocalView(findViewById(R.id.videoViewLocalSmall));
//                videoViewLocalSmall3.setMirror(true);
//                NERtcVideoView videoViewLocalSmall4 = findViewById(R.id.videoViewLocalSmall);
//                getVideoCall().setupRemoteView(findViewById(R.id.videoViewLocalSmall), usersid);
//                videoViewLocalSmall4.setMirror(true);
//                NERtcVideoView videoViewLocalSmall5 = findViewById(R.id.videoViewRemote);
//                getVideoCall().setupLocalView(findViewById(R.id.videoViewRemote));
//                videoViewLocalSmall5.setMirror(true);

            }

            @Override
            protected void onFastClick() {

            }
        });

        icMicrophone.setOnClickListener(v -> {
            isOpenMicrophone = !isOpenMicrophone;
            getVideoCall().muteLocalAudio(!isOpenMicrophone);
            if (isOpenMicrophone) {
                tv_microphone.setText("麦克风已打开");
                icMicrophone.setImageDrawable(ContextCompat.getDrawable(TestActivity.this, com.netease.yunxin.nertc.ui.R.drawable.icon_call_audio_on));
            } else {
                tv_microphone.setText("麦克风已关闭");
                icMicrophone.setImageDrawable(ContextCompat.getDrawable(TestActivity.this, com.netease.yunxin.nertc.ui.R.drawable.icon_call_audio_off));
            }
        });
        NIMClient.getService(MsgServiceObserve.class).observeMsgStatus(statusObserver, true);
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, true);
        findViewById(R.id.videoViewLocalSmall).setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (isTheLocalTime) {
                    // 展示远端画面
                    NERtcVideoView videoViewLocalSmall2 = findViewById(R.id.videoViewRemote);
                    videoViewLocalSmall2.setVisibility(View.VISIBLE);
                    getVideoCall().setupRemoteView(findViewById(R.id.videoViewRemote), usersid);
                    videoViewLocalSmall2.setMirror(false);
                    // 设置本地预览小视频窗口
                    NERtcVideoView videoViewLocalSmall = findViewById(R.id.videoViewLocalSmall);
                    videoViewLocalSmall.setVisibility(View.VISIBLE);
                    getVideoCall().setupLocalView(findViewById(R.id.videoViewLocalSmall));
                    videoViewLocalSmall.setMirror(false);
                    AVChatSoundPlayer.Companion.instance().stop(TestActivity.this);
                } else {
                    // 展示远端画面
                    NERtcVideoView videoViewLocalSmall = findViewById(R.id.videoViewLocalSmall);
                    videoViewLocalSmall.setVisibility(View.VISIBLE);
                    getVideoCall().setupRemoteView(findViewById(R.id.videoViewLocalSmall), usersid);
                    videoViewLocalSmall.setMirror(false);
                    // 设置本地预览小视频窗口
                    NERtcVideoView videoViewLocalSmall2 = findViewById(R.id.videoViewRemote);
                    videoViewLocalSmall2.setVisibility(View.VISIBLE);
                    getVideoCall().setupLocalView(findViewById(R.id.videoViewRemote));
                    videoViewLocalSmall2.setMirror(false);
                    AVChatSoundPlayer.Companion.instance().stop(TestActivity.this);
                }
                isTheLocalTime = !isTheLocalTime;
            }

            @Override
            protected void onFastClick() {

            }
        });

        LiveEventBus.<IMMessage>get("receivedGift").observe(this, imMessage -> {
            if (getLifecycle().getCurrentState() == Lifecycle.State.RESUMED) {
                if (imMessage.getAttachment() instanceof GiftAttachment) {
                    GiftMessageBean giftMessageBean = ((GiftAttachment) imMessage.getAttachment()).getData();
                    if (giftMessageBean.getGift().getAnimationSrc() != null && !giftMessageBean.getGift().getAnimationSrc().isEmpty()) {
                        GiftGifDialog giftGifDialog = new GiftGifDialog(this, giftMessageBean.getGift().getAnimationSrc());
                        new XPopup.Builder(this)
                                .hasShadowBg(false)
                                .dismissOnBackPressed(false)
                                .asCustom(giftGifDialog)
                                .show();
                    }
                    GiftSuspensionDialog giftSuspensionDialog = new GiftSuspensionDialog(this);
                    giftSuspensionDialog.setData(imMessage);
                    new XPopup.Builder(this)
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                            .isViewMode(true)
                            .isRequestFocus(false)
                            .isClickThrough(true)
                            .hasShadowBg(false)
                            .dismissOnBackPressed(false)
                            .offsetY(DensityUtil.dip2px(this, 366))
                            .asCustom(giftSuspensionDialog)
                            .show();
                }
            }
        });
        loopUtil = new LoopUtil(this);
        initData();
    }

    private void initData() {
        if (ourinfoBean != null) {
            acceptcode = ourinfoBean.getCode();
            acceptmsg = ourinfoBean.getMsg();
            if (ourinfoBean.getCode() != 0) {
                ToastUtils.showShort(ourinfoBean.getMsg());
                return;
            }
            if (ourinfoBean.getData() != null) {
                if (ourinfoBean.getData().getOtherInfo() != null) {
                    name = ourinfoBean.getData().getOtherInfo().getName();
                    city = ourinfoBean.getData().getOtherInfo().getCity();
                    if (ourinfoBean != null) {
                        if (ourinfoBean.getData() != null) {
                            if (ourinfoBean.getData().getOtherInfo() != null) {
                                String persionSign = ourinfoBean.getData().getOtherInfo().getPersionSign();
                                TextView viewById = findViewById(R.id.tv_sign);
                                viewById.setText(persionSign);
                            }
                        }
                    }


                    if (name != null) {
                        tv_callername = findViewById(R.id.tv_callername);
                        tv_callername.setText(name);
                        if (flag == 0) {
                            //表示被叫
                            tv_waitaccept.setText(name + getString(R.string.mi_yaoqingninshipintonghua));
                        } else {
                            //表示呼叫方
                            tv_waitaccept.setText(getString(R.string.mi_zhengzaidengdai) + name + getString(R.string.mi_jieshounindetonghuayaoqing));
                        }
                    }
                    if (ourinfoBean.getData().getOtherInfo().getIcon() != null) {
                        img_heads = findViewById(R.id.img_heads);
                        Glide.with(MyAppliaction.getContext())
                                .load(url + ourinfoBean.getData().getOtherInfo().getIcon())
                                .apply(RequestOptions.bitmapTransform(new CircleCrop()))//圆角半径
                                .into(img_heads);
                    }
                }
                if (ourinfoBean.getData().getOtherInfo().getHost() == 0) {
                    //代表主播
                    tv_zhuboshouyi.setText(getString(R.string.mi_meifenzhongshouyi) + ourinfoBean.getData().getStandard() + getString(R.string.mi_jifenjietonghoukaishijifei));
                    if (city != null) {
                        TextView tv_location = findViewById(R.id.tv_location);
                        tv_location.setText(city);
                        img_location.setVisibility(View.VISIBLE);
                    }
                } else {
                    //代表用户
                    tv_zhuboshouyi.setText(getString(R.string.mi_zhuboliaotian) + ourinfoBean.getData().getStandard() + getString(R.string.mi_jiangzaijietonghoujinxingjifei));
                    img_location.setVisibility(View.GONE);
                }
            }
        }
    }

    private List<SendMessageBean> chatList = new ArrayList<SendMessageBean>();

    private com.netease.nimlib.sdk.Observer<List<IMMessage>> incomingMessageObserver =
            messages -> {
                // 处理新收到的消息，为了上传处理方便，SDK 保证参数 messages 全部来自同一个聊天对象。
                IMMessage msg = messages.get(messages.size() - 1);
                if (msg == null || msg.isDeleted() || msg.getContent() == null) return;
                if (msg.getSessionId().equals(usersid)){
                    chatList.add(new SendMessageBean(msg.getContent(), msg.getFromNick(), false));
                    adapter.setList(chatList);
                    chatView.post(new Runnable() {
                        @Override
                        public void run() {
                            chatView.scrollToPosition(chatList.size() - 1);
                        }
                    });
                }
            };

    private com.netease.nimlib.sdk.Observer<IMMessage> statusObserver = msg -> {
        // 消息状态变化
        if (Objects.equals(msg.getSessionId(), usersid)) {
            if (msg.getContent() == null) return;
            // 自己发送的消息
            chatList.add(new SendMessageBean(msg.getContent(), msg.getFromNick(), false));
            adapter.setList(chatList);
            chatView.post(new Runnable() {
                @Override
                public void run() {
                    chatView.scrollToPosition(chatList.size() - 1);
                }
            });
        }
    };

    /**
     * 美颜处理
     */
    private void facialTreatment() {
        NERtcEx.getInstance().setVideoCallback(neRtcVideoFrame -> {
            FURenderInputData inputData = new FURenderInputData(neRtcVideoFrame.width, neRtcVideoFrame.height);
            inputData.setTexture(new FURenderInputData.FUTexture(FUInputTextureEnum.FU_ADM_FLAG_EXTERNAL_OES_TEXTURE, neRtcVideoFrame.textureId));
            FURenderOutputData fuRenderOutputData = FURenderKit.getInstance().renderWithInput(inputData);
            if (fuRenderOutputData.getTexture() != null && fuRenderOutputData.getTexture().getTexId() > 0) {
                if (!isFirstInit) {
                    isFirstInit = true;
                    FaceBeauty faceBeauty = FaceBeautySource.getDefaultFaceBeauty();
                    bindCurrentRenderer(faceBeauty);
                }
                if (neRtcVideoFrame.format == NERtcVideoFrame.Format.TEXTURE_OES) {
                    neRtcVideoFrame.format = NERtcVideoFrame.Format.TEXTURE_RGB;
                }
                neRtcVideoFrame.textureId = fuRenderOutputData.getTexture().getTexId();
                return true;
            } else {
                return false;
            }
        }, false);
    }

    /**
     * FURenderKit加载当前特效
     */
    public void bindCurrentRenderer(FaceBeauty faceBeauty) {
        FURenderKit.getInstance().setFaceBeauty(faceBeauty);
        FUAIKit.getInstance().setMaxFaces(4);
        ExpressionRecognition expressionRecognition = new ExpressionRecognition(new FUBundleData(DemoConfig.BUNDLE_LANDMARKS));
        expressionRecognition.setLandmarksType(FUAITypeEnum.FUAITYPE_FACELANDMARKS239);
        FURenderKit.getInstance().getPropContainer().addProp(expressionRecognition);
    }

    //    将StatusBar设置为透明
    public void setStatusBarTranslucent() {
        StatusBarUtil.setTranslucentForImageViewInFragment(this,
                0, null);
        StatusBarUtil.setLightMode(this);
    }


    /**
     * 请求头传参方式
     */
    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }


    @Override// 资源释放
    protected void releaseAndFinish(boolean finishCall) {
        super.releaseAndFinish(finishCall);
        if (finishCall) {
            doHangup(null);
        }
    }

    @Override
    public void doOnCreate(@androidx.annotation.Nullable Bundle savedInstanceState) {
        super.doOnCreate(savedInstanceState);
        callerAccId = getCallParam().getCallerAccId();
        p2pCalledAccId = getCallParam().getP2pCalledAccId();
        LogUtils.i("CalledAccId", p2pCalledAccId);
        //主叫accid
        LogUtils.i("callerAccId", callerAccId);
        LogUtils.i("tokeninfo", token);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);

        findViewById(R.id.rele_hujiaofang).setVisibility(View.VISIBLE);

    }

    /**
     * 预检接口
     *
     * @param extra
     * @param toUserId
     * @param token
     */
    private void impcall(String extra, String toUserId, String token) {
        getRequest();
        NetUtils.getInstance().getApiService().getimPre(extra, toUserId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        if (numberBean != null) {
                            String data = numberBean.getData();
                            String decryptStr = null;
                            try {
                                decryptStr = AESUtil.aesDecryptString(data, KEY);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            com.blankj.utilcode.util.LogUtils.i("decryptStrstest", decryptStr);
                            Gson gson = new Gson();
                            ourinfoBean = gson.fromJson(decryptStr, OurinfoBean.class);
                            if (ourinfoBean != null) {
                                if (ourinfoBean.getData() != null) {
                                    double standard = ourinfoBean.getData().getStandard();//主播收益/顾客价格
                                }
                            }
                            acceptcode = ourinfoBean.getCode();
                            acceptmsg = ourinfoBean.getMsg();
                            if (ourinfoBean.getCode() == 0) {

                            } else {
                                ToastUtils.showShort(ourinfoBean.getMsg());
                            }
                            if (ourinfoBean != null) {
                                if (ourinfoBean.getData() != null) {
                                    if (ourinfoBean.getData().getOtherInfo() != null) {
                                        name = ourinfoBean.getData().getOtherInfo().getName();
                                        city = ourinfoBean.getData().getOtherInfo().getCity();
                                        if (ourinfoBean != null) {
                                            if (ourinfoBean.getData() != null) {
                                                if (ourinfoBean.getData().getOtherInfo() != null) {
                                                    String persionSign = ourinfoBean.getData().getOtherInfo().getPersionSign();
                                                    TextView viewById = findViewById(R.id.tv_sign);
                                                    viewById.setText(persionSign);
                                                }
                                            }
                                        }


                                        if (name != null) {
                                            tv_callername = findViewById(R.id.tv_callername);
                                            tv_callername.setText(name);
                                            if (flag == 0) {
                                                //表示被叫
                                                tv_waitaccept.setText(name + getString(R.string.mi_yaoqingninshipintonghua));
                                            } else {
                                                //表示呼叫方
                                                tv_waitaccept.setText(getString(R.string.mi_zhengzaidengdai) + name + getString(R.string.mi_jieshounindetonghuayaoqing));
                                            }
                                        }
                                        if (ourinfoBean.getData().getOtherInfo().getIcon() != null) {
                                            img_heads = findViewById(R.id.img_heads);
                                            Glide.with(MyAppliaction.getContext())
                                                    .load(url + ourinfoBean.getData().getOtherInfo().getIcon())
                                                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))//圆角半径
                                                    .into(img_heads);
                                        }


                                    }
                                    if (ourinfoBean.getData().getOtherInfo().getHost() == 0) {
                                        //代表主播
                                        tv_zhuboshouyi.setText(getString(R.string.mi_meifenzhongshouyi) + ourinfoBean.getData().getStandard() + getString(R.string.mi_jifenjietonghoukaishijifei));
                                        if (city != null) {
                                            TextView tv_location = findViewById(R.id.tv_location);
                                            tv_location.setText(city);
                                            img_location.setVisibility(View.VISIBLE);
                                        }
                                    } else {
                                        //代表用户
                                        tv_zhuboshouyi.setText(getString(R.string.mi_zhuboliaotian) + ourinfoBean.getData().getStandard() + getString(R.string.mi_jiangzaijietonghoujinxingjifei));
                                        img_location.setVisibility(View.GONE);
                                    }
                                }

                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @NotNull
    @Override
    protected NERTCCallingDelegate provideRtcDelegate() {

        return new NERtcCallDelegateForP2P() {

            @Override
            public void onUserEnter(@Nullable String userId) {
                //这里返回表示通话成功后返回的对方userid
                AtomicLong time = new AtomicLong(0L);
                tvDuration.setVisibility(View.VISIBLE);
                new LoopUtil(TestActivity.this).startLoopJob(1000, () -> {
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
                    sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
                    Date data = new Date(time.get());
                    tvDuration.setText(sdf.format(data));
                    time.addAndGet(1000);
                    return null;
                });
                usersid = userId;
//                getinCall(EXTRA, rtcchannelId + "", usersid, token);
                findViewById(R.id.rele_hujiaofang).setVisibility(View.GONE);
                findViewById(R.id.callerOperationGroup).setVisibility(View.GONE);
                findViewById(R.id.calledOperationGroup).setVisibility(View.GONE);
                findViewById(R.id.llOnTheCallOperation).setVisibility(View.VISIBLE);
                imageSmallWindow.setVisibility(View.VISIBLE);
                ic_fanzhuan.setVisibility(View.VISIBLE);
                if (startPreview) {
                    NERtcEx.getInstance().stopVideoPreview();
                    startPreview = false;
                }
                // 展示远端画面
                findViewById(R.id.videoViewRemote).setVisibility(View.VISIBLE);
                getVideoCall().setupRemoteView(findViewById(R.id.videoViewRemote), userId);

                // 销毁本地预览大视频窗口
                NERtcVideoView videoViewLocalBig = findViewById(R.id.videoViewLocalBig);
                videoViewLocalBig.release();
                videoViewLocalBig.setVisibility(View.GONE);
                // 设置本地预览小视频窗口
                NERtcVideoView videoViewLocalSmall = findViewById(R.id.videoViewLocalSmall);
                videoViewLocalSmall.setVisibility(View.VISIBLE);
                getVideoCall().setupLocalView(findViewById(R.id.videoViewLocalSmall));
                videoViewLocalSmall.setMirror(false);
                AVChatSoundPlayer.Companion.instance().stop(TestActivity.this);
                loopUtil.startLoopJob(60 * 1000, () -> {
                    getinCall(EXTRA, rtcchannelId + "", usersid, token);
                    return null;
                });
            }

            @Override // 主要用户取消
            public void onCancelByUserId(@Nullable String userId) {
                super.onCancelByUserId(userId);
                AVChatSoundPlayer.Companion.instance().stop(TestActivity.this);
                Toast.makeText(TestActivity.this, "用户已取消", Toast.LENGTH_SHORT).show();
                finishAndRemoveTask();
            }

            @Override
            public void onJoinChannel(@androidx.annotation.Nullable String accId, long uid, @androidx.annotation.Nullable String channelName, long rtcChannelId) {
                super.onJoinChannel(accId, uid, channelName, rtcChannelId);
                AVChatSoundPlayer.Companion.instance().stop(TestActivity.this);
                token = MmkvUtil.INSTANCE.decodeString(TOKEN);
                rtcchannelId = rtcChannelId;
                TestActivity.this.channelName = channelName;
                //当前电话已接通
            }

            @Override// 被叫用户拒绝
            public void onRejectByUserId(@Nullable String userId) {
                super.onRejectByUserId(userId);
                AVChatSoundPlayer.Companion.instance().stop(TestActivity.this);
                ToastUtils.showShort(R.string.mi_jujuelnindetonghuayaoqing);
                finishAndRemoveTask();
            }

            @Override// 通过结束
            public void onCallEnd(@Nullable String userId) {
                super.onCallEnd(userId);
                loopUtil.stopLoopJob();
                finishAndRemoveTask();
            }

            @Override// 被叫用户占线
            public void onUserBusy(@Nullable String userId) {
                super.onUserBusy(userId);
                Toast.makeText(TestActivity.this, "用户占线", Toast.LENGTH_SHORT).show();
                AVChatSoundPlayer.Companion.instance().stop(TestActivity.this);
                finishAndRemoveTask();
            }

            @Override
            public void onCameraAvailable(@androidx.annotation.Nullable String userId, boolean isVideoAvailable) {
                super.onCameraAvailable(userId, isVideoAvailable);
            }

            @Override
            public void onVideoMuted(@androidx.annotation.Nullable String userId, boolean isMuted) {
                super.onVideoMuted(userId, isMuted);
                if (isMuted) {
                    findViewById(R.id.videoViewRemote).setVisibility(View.GONE);
                    findViewById(R.id.constraintCloseCamera).setVisibility(View.VISIBLE);
                } else {
                    findViewById(R.id.videoViewRemote).setVisibility(View.VISIBLE);
                    findViewById(R.id.constraintCloseCamera).setVisibility(View.GONE);
                }
            }

            // todo 根据code 判断提示用户
            @Override
            public void onCallFinished(@androidx.annotation.Nullable Integer code, @androidx.annotation.Nullable String msg) {
                super.onCallFinished(code, msg);
                if (code != null) {
                    String massage;
                    switch (code) {
                        case 2001:
                            massage = "其他端已经接受";
                            break;
                        case 2002:
                            massage = "用户已拒绝";
                            break;
                        case 2011:
                            massage = "断开连接";
                            break;
                        default:
                            massage = "未知错误";
                            break;
                    }
                    Toast.makeText(TestActivity.this, massage, Toast.LENGTH_SHORT).show();
                }
                finishAndRemoveTask();
            }
        };
    }

    /**
     * @param extra
     * @param channelId
     * @param toUserId
     * @param token
     */
    private void getinCall(String extra, String channelId, String toUserId, String token) {
        getRequest();
        String channelName = getCallParam().getRtcChannelName();
        if (channelName == null || channelName.isEmpty()) {
            channelName = this.channelName;
        }
        LogUtils.i("getRtcChannelName", channelName);
        NetUtils.getInstance().getApiService().getinCall(extra, channelId, toUserId, channelName, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        Log.e("VIDEO", "开始通话");
                        MmkvUtil.INSTANCE.encode("isVideo", true);
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            com.blankj.utilcode.util.LogUtils.i("decryptStr1000000", decryptStr);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Gson gson = new Gson();
                        KouFeiBean kouFeiBean = gson.fromJson(decryptStr, KouFeiBean.class);
                        if (kouFeiBean != null) {
                            if (CallLogId != null) {
                                CallLogId = kouFeiBean.getData().getCallLogId();
                            }

                            if (kouFeiBean.getData() != null) {
                                if (kouFeiBean.getData().getMind() != 0) {
                                    ToastUtils.showShort(getString(R.string.mi_yujidangqianketonghuashengyu) + kouFeiBean.getData().getRest() + getString(R.string.mi_fenzhong));
                                }
                            }
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr619", decryptStr);
                        com.blankj.utilcode.util.LogUtils.i("decryptStr619", "云信返回id" + rtcchannelId + "" + "对方id" + usersid);
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showShort(e.getMessage());
                        if (e instanceof SocketTimeoutException){
                            doHangup();
                            finishAndRemoveTask();
                            Intent intent = new Intent(TestActivity.this, HomeActivity.class);
                            startActivity(intent);
                            return;
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getstopCall(String extra, String channelId, String token) {
        getRequest();
        NetUtils.getInstance().getApiService().getstopCall(extra, channelId, getCallParam().getRtcChannelName(), token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr6190", decryptStr);

                    }


                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    ServiceConnection mVideoServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 获取服务的操作对象
            FloatVideoWindowService.FloatVideoWindowBinder binder = (FloatVideoWindowService.FloatVideoWindowBinder) service;
            binder.getService().setVideoViewRemote(getVideoCall());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    //启动悬浮窗
    public void startVideoService() {
        if (usersid == null) {
            return;
        }
        if (!checkFloatPermission(this)) {
            Toast.makeText(this, "无法开启小窗视频通话，请允许权限", Toast.LENGTH_SHORT).show();
            new XPopup.Builder(this)
                    .asCustom(new SuspendedWindowDialog(this))
                    .show();
            return;
        }
        moveTaskToBack(true);//最小化Activity
        Intent intent = new Intent(this, FloatVideoWindowService.class);//开启服务显示悬浮框
        intent.putExtra("userId", usersid);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
        bindService(intent, mVideoServiceConnection, Context.BIND_AUTO_CREATE);
    }

    //判断是否开启悬浮窗权限   context可以用你的Activity.或者tiis
    public boolean checkFloatPermission(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                if (appOpsMgr == null)
                    return false;
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), context
                        .getPackageName());
                return mode == AppOpsManager.MODE_ALLOWED;
            } else {
                return Settings.canDrawOverlays(context);
            }
        }
    }

    @Override
    protected void onDestroy() {
        FURenderKit.getInstance().release();
        AVChatSoundPlayer.Companion.instance().stop(TestActivity.this);
        NIMClient.getService(MsgServiceObserve.class).observeMsgStatus(statusObserver, false);
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, false);
        LogUtils.i("CallLogId", rtcchannelId);
        if (serverIsRunning(FloatVideoWindowService.class.getName())) {
            Intent intent = new Intent(this, FloatVideoWindowService.class);
            unbindService(mVideoServiceConnection);
            stopService(intent);
        }
        Integer hostAudit = MmkvUtil.INSTANCE.decodeInt(HOSTAUDIT);
        Log.e("VIDEO", "结束通话");
        MmkvUtil.INSTANCE.encode("isVideo", false);
        if (hostAudit != null && hostAudit == 0 && rtcchannelId != 0) {
            LiveEventBus.<String>get("showEvaluateDialog").postDelay(String.valueOf(rtcchannelId), 200);
        }
        EventBus.getDefault().unregister(this);
        doHangup();
        super.onDestroy();
        finishAndRemoveTask();
    }

    /**
     * App前后台状态
     */
    public boolean isForeground = false;

    @Override
    protected void onResume() {
        super.onResume();
        if (!isForeground) {
            //由后台切换到前台
            isForeground = true;
        }
        if (serverIsRunning(FloatVideoWindowService.class.getName())) {
            Intent intent = new Intent(this, FloatVideoWindowService.class);
            unbindService(mVideoServiceConnection);
            stopService(intent);
            if (!isTheLocalTime) {
                // 展示远端画面
                NERtcVideoView videoViewLocalSmall2 = findViewById(R.id.videoViewRemote);
                videoViewLocalSmall2.setVisibility(View.VISIBLE);
                getVideoCall().setupRemoteView(findViewById(R.id.videoViewRemote), usersid);
                videoViewLocalSmall2.setMirror(false);
                // 设置本地预览小视频窗口
                NERtcVideoView videoViewLocalSmall = findViewById(R.id.videoViewLocalSmall);
                videoViewLocalSmall.setVisibility(View.VISIBLE);
                getVideoCall().setupLocalView(findViewById(R.id.videoViewLocalSmall));
                videoViewLocalSmall.setMirror(false);
            } else {
                // 展示远端画面
                NERtcVideoView videoViewLocalSmall = findViewById(R.id.videoViewLocalSmall);
                videoViewLocalSmall.setVisibility(View.VISIBLE);
                getVideoCall().setupRemoteView(findViewById(R.id.videoViewLocalSmall), usersid);
                videoViewLocalSmall.setMirror(false);
                // 设置本地预览小视频窗口
                NERtcVideoView videoViewLocalSmall2 = findViewById(R.id.videoViewRemote);
                videoViewLocalSmall2.setVisibility(View.VISIBLE);
                getVideoCall().setupLocalView(findViewById(R.id.videoViewRemote));
                videoViewLocalSmall2.setMirror(false);
            }
        }
    }

    /**
     * @return boolean 返回该服务是否在运行中；
     */
    private boolean serverIsRunning(String componentName) {
        ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);

        List<ActivityManager.RunningServiceInfo> runningServices
                = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (runningServices.size() <= 0) {
            return false;
        }

        for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
            if (componentName.equals(serviceInfo.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        new DelayUtil(this).delayJob(100L, () -> {
            if (!isAppOnForeground()) {
                //由前台切换到后台
                isForeground = false;
                startVideoService();
            }
            return null;
        });
    }

    /**
     * 判断app是否处于前台
     *
     * @return
     */
    public boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();
        /**
         * 获取Android设备中所有正在运行的App
         */
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (usersid == null) {
            doHangup(null);
            getstopCall(EXTRA, rtcchannelId + "", token);
            finishAndRemoveTask();
            Intent intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            doHangup(null);
            getstopCall(EXTRA, rtcchannelId + "", token);
            finishAndRemoveTask();
            Intent intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(HangUpEvent event) {
        if (serverIsRunning(FloatVideoWindowService.class.getName())) {
            Intent intent = new Intent(this, FloatVideoWindowService.class);
            unbindService(mVideoServiceConnection);
            stopService(intent);
        }
        doHangup(null);
        getstopCall(EXTRA, rtcchannelId + "", token);
        finishAndRemoveTask();
    }
}